package com.yjz.media.study.rtmp;

import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.ToastUtils;

import java.util.concurrent.LinkedBlockingDeque;

/**
 * 作用 :
 * 作者 : yjz
 * 时间 : 2023/11/8 17:02
 */
public class RtmpLivePush extends Thread {

    private boolean isRunning = false;

    public volatile static RtmpLivePush rtmpNativeHelper;
    private String url;

    public static RtmpLivePush getInstance() {
        if (rtmpNativeHelper == null) {
            synchronized (RtmpLivePush.class) {
                if (rtmpNativeHelper == null) {
                    rtmpNativeHelper = new RtmpLivePush();
                }
            }
        }
        return rtmpNativeHelper;
    }

    public LinkedBlockingDeque<RTMPPacket> rtmpPacketDeque = new LinkedBlockingDeque<>();

    public void addPacket(RTMPPacket rtmpPacket) {
        if (rtmpPacket == null || rtmpPacket.buffer == null || rtmpPacket.buffer.length == 0) {
            return;
        }
        rtmpPacketDeque.add(rtmpPacket);
    }

    /**
     * 开始推流
     *
     * @param url 推流地址
     */
    public void startPush(String url) {
        this.url = url;
        ThreadUtils.getFixedPool(3).execute(this);
    }

    /**
     * 停止推流
     */
    public void stopPush() {
        isRunning = false;
        RTMPNativeHelper.getInstance().disconnect();
    }

    /**
     * 获取推流的状态
     */
    public boolean isRunning() {
        return isRunning;
    }

    @Override
    public void run() {
        super.run();
        isRunning = RTMPNativeHelper.getInstance().connectRTMP(url);
        if (!isRunning) {
            ThreadUtils.getMainHandler().post(new Runnable() {
                @Override
                public void run() {
                    ToastUtils.showShort("连接失败！");
                }
            });
            return;
        }

        while (isRunning) {
            if (rtmpPacketDeque.isEmpty()) {
                continue;
            }
            try {
                RTMPPacket rtmpPacket = rtmpPacketDeque.take();
                if (rtmpPacket.getBuffer() != null && rtmpPacket.getBuffer().length != 0) {
                    RTMPNativeHelper.getInstance().sendData(rtmpPacket.buffer, rtmpPacket.buffer.length, rtmpPacket.type);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                ThreadUtils.getMainHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtils.showShort("InterruptedException: " + e.getMessage());
                    }
                });
            }
        }
    }
}
